import { api } from './api'

interface LoginParams {
  username: string
  password: string
}

interface RegisterParams {
  username: string
  password: string
  confirmPassword: string
}

interface LoginResponse {
  code: number
  data: {
    user_id: number
    username: string
    access_token: string
    expires_at: number
  }
  msg: string
  tracers: string
}

interface RegisterResponse {
  code: number
  data: any
  msg: string
  tracers: string
}

export const auth = {
  // 注册
  async register(params: RegisterParams): Promise<RegisterResponse> {
    try {
      const response = await api.post<RegisterResponse>('/api/v1/users/register', params)
      return response
    } catch (error) {
      throw error
    }
  },
  // 登录
  async login(params: LoginParams): Promise<LoginResponse> {
    try {
      const response = await api.post<LoginResponse>('/api/v1/users/login', params)
      // 只有当code为0时才认为登录成功
      if (response.code === 0 && response.data.access_token) {
        localStorage.setItem('token', response.data.access_token)
        localStorage.setItem('username', response.data.username)
        localStorage.setItem('user_id', response.data.user_id.toString())
      }
      return response
    } catch (error) {
      throw error
    }
  },

  // 注销
  async logout() {
    try {
      const token = this.getToken()
      if (token) {
        await api.post('/api/v1/users/logout')
      }
      localStorage.removeItem('token')
      // 清理其他本地存储的用户信息
      localStorage.removeItem('username')
      localStorage.removeItem('user_id')
    } catch (error) {
      console.error('退出登录失败:', error)
      throw error
    }
  },

  // 获取当前token
  getToken(): string | null {
    return localStorage.getItem('token')
  },

  // 检查是否已登录
  isAuthenticated(): boolean {
    return !!this.getToken()
  },

  // 获取当前用户信息
  async getCurrentUser() {
    const { userApi } = await import('./user')
    return userApi.getCurrentUser()
  }
}